from django.shortcuts import render
from rest_framework import viewsets, views
from rest_framework.decorators import api_view
from honorCupboard.models import Device,DeviceParams, Contract
from honorCupboard.serializers import ContractSerializer
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.decorators import action
from rest_framework.response import Response
from django.http import HttpResponse
import logging

from openpyxl import Workbook   
from openpyxl.writer.excel import save_virtual_workbook
from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment


class ContractViewSet(viewsets.ModelViewSet):
    """
    CustomerSet API
    """
    queryset = Contract.objects.all()
    serializer_class = ContractSerializer
    permission_classes = (AllowAny,)

    @action(methods=['get','post'], detail=False)
    def export(self, request, pk=None):
        # print(request.data)
        wb = Workbook()
        ws = wb.active
        ws.title = "TestSheet"
        # 处理标题 
        ws.merge_cells('A1:I2')
        ws['A1'] = '默贝特荣耀柜订单参数表'
        
        #定义字体
        # font = Font(b=True, color="FF0000")
        al = Alignment(horizontal="center", vertical="center")
        ws['A1'].alignment = al

        ws.merge_cells('J1:L2')
        bordered(ws,'A1:L2')

        ws['J1'] = '编号：'
        ws['J1'].alignment = al
        
        # 处理标题  end
        # 处理合同参数

        ws.merge_cells('A3:L3')
        bordered(ws,'A3:L3')
        ws['A3'] = '1.合同参数（带*项必填，以下同，未填写为标配）'

        ws.merge_cells('A4:B4')
        ws.merge_cells('C4:F4')
        ws.merge_cells('G4:H4')
        ws.merge_cells('I4:L4')
        bordered(ws,'A4:B4')
        bordered(ws,'C4:F4')
        bordered(ws,'G4:H4')
        bordered(ws,'I4:L4')

        ws['A4'] = '合同单位'
        ws['G4'] = '联系人'

        ws.merge_cells('A5:B5')
        ws.merge_cells('C5:F5')
        ws.merge_cells('G5:H5')
        ws.merge_cells('I5:L5')
        bordered(ws,'A5:B5')
        bordered(ws,'C5:F5')
        bordered(ws,'G5:H5')
        bordered(ws,'I5:L5')
        ws['A5'] = '项目名称'
        ws['G5'] = '手机'

        ws.merge_cells('A6:B6')
        ws.merge_cells('C6:F6')
        ws.merge_cells('G6:H6')
        ws.merge_cells('I6:L6')
        bordered(ws,'A6:B6')
        bordered(ws,'C6:F6')
        bordered(ws,'G6:H6')
        bordered(ws,'I6:L6')
        ws['A6'] = '设备号'
        ws['G6'] = '固定电话'

        ws.merge_cells('A7:B7')
        ws.merge_cells('C7:F7')
        ws.merge_cells('G7:H7')
        ws.merge_cells('I7:L7')
        bordered(ws,'A7:B7')
        bordered(ws,'C7:F7')
        bordered(ws,'G7:H7')
        bordered(ws,'I7:L7')
        ws['A7'] = '订单数量'
        ws['G7'] = '传真'

        ws.merge_cells('A8:B8')
        ws.merge_cells('C8:F8')
        ws.merge_cells('G8:H8')
        ws.merge_cells('I8:L8')
        bordered(ws,'A8:B8')
        bordered(ws,'C8:F8')
        bordered(ws,'G8:H8')
        bordered(ws,'I8:L8')
        ws['A8'] = '交货日期'
        ws['G8'] = '发货地址'

        ws.merge_cells('A9:B9')
        ws.merge_cells('C9:F9')
        ws.merge_cells('G9:H9')
        ws.merge_cells('I9:L9')
        bordered(ws,'A9:B9')
        bordered(ws,'C9:F9')
        bordered(ws,'G9:H9')
        bordered(ws,'I9:L9')
        ws['A9'] = ''
        ws['G9'] = '安装地址'

        # 合同结束

        # 控制柜参数
        setPartTitle(ws, 'A10:L10', '2.控制柜参数')
        setMergeCell(ws, 'A11:B16', '控制柜')
        setMergeCell(ws, 'C11:F14', 'NICE-DDDV001-W224')
        setMergeCell(ws, 'C15:F16', '需要')



        # 控制柜结束

        # ws.sheet_properties.tabColor = "1072BA"

        # content = "attachment; filename={filename}".format(filename="test.xlsx")
        # response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel')
        # response['Content-Disposition'] = content
        # wb.save(response)

        # return response
        return Response({'status': 'password set'})


def setPartTitle(ws, cell_range, title):
    ws.merge_cells(cell_range)
    bordered(ws, cell_range)
    first_cell = ws[cell_range.split(":")[0]]
    first_cell.value = title

def setMergeCell(ws, cell_range, value):
    ws.merge_cells(cell_range)
    bordered(ws, cell_range)
    first_cell = ws[cell_range.split(":")[0]]
    first_cell.value = value


    


def bordered(ws,cell_range):
    thin = Side(border_style="thin", color="000000")
    border = Border(top=thin, left=thin, right=thin, bottom=thin)
    top = Border(top=border.top)
    left = Border(left=border.left)
    right = Border(right=border.right)
    bottom = Border(bottom=border.bottom)
    # 定义边框
    rows = ws[cell_range]
    logging.info('info message')  

    for cell in rows[0]:
        cell.border = cell.border + top
    for cell in rows[-1]:
        cell.border = cell.border + bottom

    for row in rows:
        l = row[0]
        r = row[-1]
        l.border = l.border + left
        r.border = r.border + right     

    

# def style_range(ws, cell_range, border=Border(), fill=None, font=None, alignment=None):
#     """
#     Apply styles to a range of cells as if they were a single cell.

#     :param ws:  Excel worksheet instance
#     :param range: An excel range to style (e.g. A1:F20)
#     :param border: An openpyxl Border
#     :param fill: An openpyxl PatternFill or GradientFill
#     :param font: An openpyxl Font object
#     """

#     top = Border(top=border.top)
#     left = Border(left=border.left)
#     right = Border(right=border.right)
#     bottom = Border(bottom=border.bottom)

#     first_cell = ws[cell_range.split(":")[0]]
#     if alignment:
#         ws.merge_cells(cell_range)
#         first_cell.alignment = alignment

#     rows = ws[cell_range]
#     if font:
#         first_cell.font = font

#     for cell in rows[0]:
#         cell.border = cell.border + top
#     for cell in rows[-1]:
#         cell.border = cell.border + bottom

#     for row in rows:
#         l = row[0]
#         r = row[-1]
#         l.border = l.border + left
#         r.border = r.border + right
#         if fill:
#             for c in row:
#                 c.fill = fill
